package org.jeecg.modules.demo.interceptor;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.jeecg.modules.demo.constant.BaseContext;
import org.jeecg.modules.demo.constant.JwtClaimsConstant;
import org.jeecg.modules.demo.pojo.JwtProperties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.modules.demo.pojo.drfJwtUtil;

/**
 * jwt令牌校验的拦截器
 */
// 移除@Component注解，改为在配置类中注册
@Slf4j
public class JwtTokenUserInterceptor implements HandlerInterceptor {

     @Autowired
     private JwtProperties jwtProperties;

    /**
     * 校验jwt
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }

        String requestURI = request.getRequestURI();
        log.info("拦截到请求: {}", requestURI);
        
        // 对于登录和验证码接口直接放行
        if (requestURI.contains("/drf/Users/login") || requestURI.contains("/drf/Users/captcha")) {
            log.info("放行登录或验证码接口: {}", requestURI);
            return true;
        }

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getUserTokenName());

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            // 检查token是否为空，避免后续解析时出现异常
            if (token == null || token.isEmpty()) {
                log.error("JWT令牌为空");
                response.setStatus(401);
                return false;
            }
            Claims claims = drfJwtUtil.parseJWT(jwtProperties.getUserSecretKey(), token);
            
            // 检查claims是否包含用户ID
            Object userIdObj = claims.get(JwtClaimsConstant.USER_ID);
            if (userIdObj == null) {
                log.error("JWT claims中未找到用户ID");
                response.setStatus(401);
                return false;
            }
            
            Long userId = Long.valueOf(userIdObj.toString());
            log.info("当前用户id：{}", userId);
            BaseContext.setCurrentId(userId);
            //3、通过，放行
            return true;
        } catch (JwtException ex) {
            //4、不通过，响应401状态码
            log.error("JWT校验失败，token格式错误: ", ex);
            response.setStatus(401);
            return false;
        } catch (Exception ex) {
            //4、不通过，响应401状态码
            log.error("JWT校验失败: ", ex);
            response.setStatus(401);
            return false;
        }
    }
}